package com.imooc.mq;

import com.imooc.api.mq.RabbitMQSMS2Config;
import com.imooc.api.mq.RabbitMQSMSConfig;
import com.imooc.pojo.MQ.SMSContentQO;
import com.imooc.utils.GsonUtils;
import com.imooc.utils.SMSUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.amqp.rabbit.annotation.RabbitListener;


/**
 * 短信监听消费者
 */
@Slf4j
@Component
public class RabbitMQSMSConsumer {

    @Autowired
    private SMSUtils smsUtils;

    /**
     * 监听队列，并且处理消息
     */
    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
    public void watchQueue(String payload, Message message) throws Exception {
        String msg = payload;
        log.info("payload:{}", msg);

        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        log.info("routingKey:{}", routingKey);

        if (routingKey.equalsIgnoreCase(RabbitMQSMSConfig.SMS_ROUTING_KEY_SEND_LOGIN)) {
            // 此处为短信发送的消息消费处理

            SMSContentQO contentQO = GsonUtils.stringToBean(msg, SMSContentQO.class);
            log.info("contentQO:{}", contentQO);
            smsUtils.sendSMS(contentQO.getMobile(), contentQO.getContent());
        }
    }

    @RabbitListener(queues = RabbitMQSMS2Config.SMS_QUEUE)
    public void watchQueue2(Message message, Channel channel) throws Exception {
        try {
            String msg = new String(message.getBody());
            SMSContentQO contentQO = GsonUtils.stringToBean(msg, SMSContentQO.class);

            log.info(" 接收到短信请求：手机号 = {}, 内容 = {}", contentQO.getMobile(), contentQO.getContent());
            smsUtils.sendSMS(contentQO.getMobile(), contentQO.getContent());

            /**
             * 确认
             * deliveryTag: 消息投递标签
             * multiple:    批量确认所有消费者获得的消息
             */
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);

        } catch (Exception e) {
            e.printStackTrace();
            /**
             * deliveryTag: 消息投递标签
             * multiple:    批量确认所有消费者获得的消息
             * requeue:     true:重回队列 false:丢弃消息
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, true);
        }
    }
}
